<template>
  <BasicModal
    v-bind="$attrs"
    @ok="handleSubmint"
    :minHeight="20"
    okText="下载"
    :loading="loading"
    :confirmLoading="loading"
    @register="register"
    :title="modalTitle"
    @visible-change="handleVisibleChange"
  >
    <div class="pt-3px pr-3px">
      <BasicForm @register="registerForm">
        <template #slotFileUpload="{ model, field }">
          <a-upload
            v-model:file-list="model[field]"
            name="file"
            :before-upload="beforeUpload"
            :max-count="1"
          >
            <a-button>
              <upload-outlined />
              点击上传
            </a-button>
          </a-upload>
        </template>
      </BasicForm>
    </div>
  </BasicModal>
</template>

<script setup lang="ts">
  import { BasicModal, useModal } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { ref, nextTick, computed, h } from 'vue';
  import { getFileHash } from '/@/utils/file/download';
  import { Upload, Button } from 'ant-design-vue';

  import {
    projectDownload,
    legalitytheproject,
    remoteprojectisrunning,
  } from '/@/api/gateway/index';
  import { uploadApi } from '/@/api/system/index';
  import { getAllProject, getCurrentProjectFullpath } from '/@/api/server/project';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { UploadOutlined } from '@ant-design/icons-vue';
  import type { UploadProps } from 'ant-design-vue';

  const props = defineProps({
    info: {
      type: Object,
      default: () => {},
    },
  });
  const AUpload = Upload;
  const AButton = Button;
  const { createMessage, createConfirm } = useMessage();
  const [register] = useModal();
  const emit = defineEmits(['submitSuccess']);
  const { t } = useI18n();

  let modalTitle = computed(() => {
    return `工程下载（IP：${props.info.IPV4})`;
  });
  let loading = ref(false);
  let defaultPath = ref('');
  let listPath = ref('');
  // 表单内容
  const schemas: FormSchema[] = [
    {
      field: 'type',
      component: 'RadioGroup',
      label: '获取方式:',
      colProps: {
        span: 24,
      },
      defaultValue: '1',
      componentProps: {
        options: [
          {
            label: '默认工程',
            value: '1',
          },
          {
            label: '工程列表',
            value: '2',
          },
          {
            label: '文件选择',
            value: '3',
          },
        ],
        onChange: (e) => {
          let { target } = e;
          nextTick(() => {
            if (+target.value === 1) {
              setFieldsValue({ path: defaultPath.value });
            } else if (+target.value === 2) {
              setFieldsValue({ path: listPath.value });
            } else {
              setFieldsValue({ path: null });
            }
            clearValidate();
          });
        },
      },
      rules: [
        {
          required: true,
          // message: '请选择预配置',
          validator: async (_rule, value) => {
            if (!value) {
              /* eslint-disable-next-line */
              return Promise.reject('请选择获取方式');
            }
            return Promise.resolve();
          },
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'id',
      component: 'Select',
      label: '工程列表：',
      colProps: {
        span: 24,
      },
      ifShow: ({ values }) => {
        return +values.type === 2;
      },
      componentProps: {
        placeholder: '请选择工程',
        options: [],
        fieldNames: { label: 'Name', value: 'FullName', key: 'Name' },
        onChange: (e) => {
          setFieldsValue({ path: e });
          listPath.value = e;
        },
      },
      rules: [
        {
          required: true,
          message: '请选择工程',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'path',
      component: 'InputTextArea',
      label: '工程路径：',
      colProps: {
        span: 24,
      },
      ifShow: ({ values }) => {
        return +values.type !== 3;
      },
      dynamicDisabled: ({ values }) => {
        return +values.type !== 3;
      },
      componentProps: {
        placeholder: '请输入工程路径',
      },
      rules: [
        {
          required: true,
          message: '请输入工程路径',
          trigger: 'blur',
        },
      ],
    },
    {
      field: 'file',
      component: 'Input',
      label: '文件上传：',
      slot: 'slotFileUpload',
      colProps: {
        span: 24,
      },
      defaultValue: [],
      ifShow: ({ values }) => {
        return +values.type === 3;
      },
      rules: [
        {
          required: true,
          // message: '请上传文件',
          validator: async (_rule, value) => {
            if (!value || value.length === 0) {
              /* eslint-disable-next-line */
              return Promise.reject('请上传文件');
            }
            return Promise.resolve();
          },
          trigger: ['change', 'blur'],
        },
      ],
    },
  ];
  const [
    registerForm,
    { validateFields, resetFields, clearValidate, updateSchema, setFieldsValue },
  ] = useForm({
    labelWidth: 80,
    schemas: schemas,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 24,
    },
  });
  const beforeUpload: UploadProps['beforeUpload'] = (_file) => {
    // fileList.value = [...fileList.value, file];
    return false;
  };
  // 获取全部工程和当前工程
  async function getValueAndOptions() {
    loading.value = true;
    try {
      let resByAll = await getAllProject();
      let res = await getCurrentProjectFullpath();
      nextTick(() => {
        updateSchema({
          field: 'id',
          componentProps: {
            options: resByAll || [],
          },
        });
        defaultPath.value = res;
        setFieldsValue({ path: res });
      });
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }

  // 询问是否写入
  async function handleWrite(content) {
    return new Promise<boolean>((resolve) => {
      createConfirm({
        iconType: 'warning',
        okText: '是',
        cancelText: '否',
        title: () => h('span', '提示'),
        content: () => h('span', content),
        onOk: async () => {
          resolve(true);
        },
        onCancel() {
          resolve(false);
        },
      });
    });
  }

  // 查询远端工程是否在运行
  async function examineOperatingStatus() {
    let isOk = false;
    try {
      let res = await remoteprojectisrunning([props.info.IPV4]);
      if (res) {
        isOk = await handleWrite('工程正在运行，是否继续下载');
      } else {
        isOk = true;
      }
    } catch (_error) {
      isOk = false;
    }

    return isOk;
  }
  async function handleUpload(params) {
    let FilesSHA = await getFileHash(params.originFileObj);
    return uploadApi(
      {
        data: {
          Controller: 'GatewayManager',
          Parameters: JSON.stringify([props.info.IPV4]),
          Action: 'ProjectDownloadByUpload',
          FilesSHA: JSON.stringify([FilesSHA]),
        },
        file: params.originFileObj,
      },
      function onUploadProgress(_progressEvent: ProgressEvent) {},
    );
  }
  // 下载按钮事件
  async function handleSubmint() {
    loading.value = true;
    try {
      let res = await validateFields();
      // 询问是否写入工程
      let resByWrite = await handleWrite('是否写入工程');
      if (resByWrite) {
        // 【文件选择】逻辑
        if (+res.type === 3) {
          // 查询远端工程是否在运行并询问是否继续下载
          let resByExamineOperatingStatus = await examineOperatingStatus();
          if (resByExamineOperatingStatus) {
            // 开始上传
            let resByUpload = await Promise.all(
              res.file.map((item) => {
                return handleUpload(item);
              }),
            );
            let erroMessages = resByUpload.filter((item) => item.data.Code !== 0);
            if (erroMessages.length > 0) {
              createMessage.error(erroMessages[0].data.Message);
            } else {
              createMessage.success(t('layout.setting.operatingTitle'));
              emit('submitSuccess', {});
            }
          }
        } else {
          //【默认工程】【工程列表】逻辑
          // 查询工程文件是否合法
          let resBylegalitytheproject = await legalitytheproject([res.path]);
          if (resBylegalitytheproject) {
            // 查询远端工程是否在运行并询问是否继续下载
            let resByExamineOperatingStatus = await examineOperatingStatus();
            if (resByExamineOperatingStatus) {
              // 开始下载
              await projectDownload([props.info.IPV4, res.path]);
              createMessage.success(t('layout.setting.operatingTitle'));
              emit('submitSuccess', {});
            }
          }
        }
      }
      loading.value = false;
    } catch (_error) {
      loading.value = false;
    }
  }
  function handleVisibleChange(visible) {
    console.log(`output->props.info`, props.info);
    if (visible) {
      nextTick(() => {
        getValueAndOptions();
      });
    } else {
      emit('submitSuccess', {});
      resetFields();
    }
  }
</script>

<style lang="less" scoped></style>
